import React, { useState } from 'react';
import {
  Box,
  Button,
  Typography,
  Alert,
  Snackbar,
  Card,
  CardContent,
  TextField,
  InputAdornment,
  IconButton,
  Tooltip,
} from '@mui/material';
import {
  VideoCall,
  ContentCopy,
  Share,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { roomApi } from '@/services/api';
import { getUserId, copyToClipboard, generateRoomUrl } from '@/utils/helpers';
import { SUCCESS_MESSAGES, ERROR_MESSAGES } from '@/utils/constants';
import Loading from '../common/Loading';

const CreateRoom: React.FC = () => {
  const [isCreating, setIsCreating] = useState(false);
  const [roomUrl, setRoomUrl] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [showSuccess, setShowSuccess] = useState(false);
  const [copySuccess, setCopySuccess] = useState(false);
  
  const navigate = useNavigate();

  const handleCreateRoom = async () => {
    setIsCreating(true);
    setError(null);

    try {
      const userId = getUserId();
      const response = await roomApi.create(userId);
      
      const url = generateRoomUrl(response.roomId);
      setRoomUrl(url);
      setShowSuccess(true);
      
      console.log('房间创建成功:', response);
    } catch (error: any) {
      console.error('创建房间失败:', error);
      setError(error.message || ERROR_MESSAGES.UNKNOWN_ERROR);
    } finally {
      setIsCreating(false);
    }
  };

  const handleCopyUrl = async () => {
    if (!roomUrl) return;
    
    const success = await copyToClipboard(roomUrl);
    if (success) {
      setCopySuccess(true);
    } else {
      setError('复制链接失败，请手动复制');
    }
  };

  const handleShareUrl = async () => {
    if (!roomUrl) return;
    
    if (navigator.share) {
      try {
        await navigator.share({
          title: 'FaceTime 视频通话邀请',
          text: '点击链接加入视频通话',
          url: roomUrl,
        });
      } catch (error) {
        console.log('分享取消或失败:', error);
      }
    } else {
      // 降级到复制链接
      handleCopyUrl();
    }
  };

  const handleJoinRoom = () => {
    if (roomUrl) {
      const roomId = roomUrl.split('/').pop();
      if (roomId) {
        navigate(`/room/${roomId}`);
      }
    }
  };

  const handleCloseSuccess = () => {
    setShowSuccess(false);
  };

  const handleCloseCopySuccess = () => {
    setCopySuccess(false);
  };

  if (isCreating) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <Loading message="正在创建房间..." size={48} />
      </Box>
    );
  }

  return (
    <Box sx={{ maxWidth: 500, mx: 'auto' }}>
      {!roomUrl ? (
        <Box sx={{ textAlign: 'center' }}>
          <Typography variant="h5" gutterBottom sx={{ fontWeight: 600 }}>
            创建新的视频通话房间
          </Typography>
          <Typography variant="body1" color="text.secondary" sx={{ mb: 4 }}>
            点击下方按钮创建一个新的视频通话房间，然后分享链接给您的朋友
          </Typography>
          
          <Button
            variant="contained"
            size="large"
            startIcon={<VideoCall />}
            onClick={handleCreateRoom}
            disabled={isCreating}
            sx={{
              py: 1.5,
              px: 4,
              fontSize: '1.1rem',
              borderRadius: 2,
              boxShadow: 3,
              '&:hover': {
                boxShadow: 6,
                transform: 'translateY(-2px)',
              },
              transition: 'all 0.3s ease',
            }}
          >
            创建房间
          </Button>
        </Box>
      ) : (
        <Card elevation={2} sx={{ borderRadius: 2 }}>
          <CardContent sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom sx={{ fontWeight: 600, color: 'success.main' }}>
              🎉 房间创建成功！
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
              您的视频通话房间已准备就绪。复制下方链接分享给朋友，或直接进入房间开始通话。
            </Typography>
            
            <TextField
              fullWidth
              label="房间链接"
              value={roomUrl}
              variant="outlined"
              InputProps={{
                readOnly: true,
                endAdornment: (
                  <InputAdornment position="end">
                    <Tooltip title="复制链接">
                      <IconButton onClick={handleCopyUrl} edge="end">
                        <ContentCopy />
                      </IconButton>
                    </Tooltip>
                    {navigator.share && (
                      <Tooltip title="分享链接">
                        <IconButton onClick={handleShareUrl} edge="end">
                          <Share />
                        </IconButton>
                      </Tooltip>
                    )}
                  </InputAdornment>
                ),
              }}
              sx={{ mb: 3 }}
            />
            
            <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
              <Button
                variant="contained"
                onClick={handleJoinRoom}
                size="large"
                sx={{ flex: 1, maxWidth: 200 }}
              >
                进入房间
              </Button>
              <Button
                variant="outlined"
                onClick={() => setRoomUrl('')}
                size="large"
                sx={{ flex: 1, maxWidth: 200 }}
              >
                创建新房间
              </Button>
            </Box>
          </CardContent>
        </Card>
      )}

      {/* 错误提示 */}
      {error && (
        <Alert
          severity="error"
          onClose={() => setError(null)}
          sx={{ mt: 2 }}
        >
          {error}
        </Alert>
      )}

      {/* 成功提示 */}
      <Snackbar
        open={showSuccess}
        autoHideDuration={3000}
        onClose={handleCloseSuccess}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert onClose={handleCloseSuccess} severity="success">
          {SUCCESS_MESSAGES.ROOM_CREATED}
        </Alert>
      </Snackbar>

      {/* 复制成功提示 */}
      <Snackbar
        open={copySuccess}
        autoHideDuration={2000}
        onClose={handleCloseCopySuccess}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert onClose={handleCloseCopySuccess} severity="success">
          {SUCCESS_MESSAGES.LINK_COPIED}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default CreateRoom;